var _ljs=require("./mmlog").root("[sever/message.js]");
var _util = require("./util");
var _session = require("./session");
var _socket = require("./socket");
var _weixin = require("./channel/WeChat-API");
var _dbSession = require("./db/session");

module.exports = {
	acceptMessage: function(message) {
		//TODO 推送消息
		var keyId = message.keyId;

		var s = _session.getSessionByKeyId(keyId);
		if (s) {
			var r = _socket.sessionMessage(s.jobId, message);
			var status = r ? 1 : 0;
			_dbSession.insertMessage([message.messageId, s.sessionId, keyId, message.sendTime, message.type, message.content, status, s.user.name, s.user.image, 1]);
		} else {
			_ljs.error("消息所属会话不存在:\n", message);
		}

	},

	sendMessage: function(keyId, message, callback) {
		var s = _session.getSessionByKeyId(keyId);
		_ljs.info("回复消息:\n", message);
		_weixin.reply(s.from, message, function(data) {
			var st = data.code == 0 ? 1 : 0;
			_dbSession.insertMessage([_util.rid(), s.sessionId, keyId, new Date().getTime(), message.type, message.content, st, message.user.name, null, message.source]);
			callback && callback(data);
		});

	},
	
	queryMessageBySessionId:function(id,callback){
		_dbSession.queryMessageBySessionId(id,function(data){
			callback(_util.result(0,data));
		})
	}
}